using System;
using Hotran.UI;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Map;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Debug = UnityEngine.Debug;

namespace Roots.UI
{
    public class StartMenu : MonoBehaviour
    {
        [SerializeField] SceneTransition transition;
        [SerializeField] Button startButton;
        [SerializeField] Button playRandomButton;
        [SerializeField] CanvasGroup loading;
        
        [SerializeField] GameObject dialog;
        [SerializeField] InputField seedInput;
        [SerializeField] Slider difficultySlider;
        [SerializeField] Button generateButton;
        [SerializeField] Button cancelButton;
        
        [SerializeField] private MapGenerator mapGenerator;

        
        private void Start()
        {
            dialog.SetActive(false);
            startButton.onClick.AddListener(StartGame);
            playRandomButton.onClick.AddListener(PlayRandom);
            generateButton.onClick.AddListener(OnGenerateMapClicked);
            cancelButton.onClick.AddListener(() => dialog.SetActive(false));
        }

        private void PlayRandom()
        {
            dialog.SetActive(true);
        }

        private void StartGame()
        {
            transition.FadeOut(() => SceneManager.LoadScene(1));
        }

        private void OnGenerateMapClicked()
        {
            generateButton.onClick.RemoveListener(OnGenerateMapClicked);
            transition.FadeOut(() =>
            {
                StartCoroutine(GenerateMap(Convert.ToInt32(seedInput.text), (int)difficultySlider.value));
            });
        }

        private IEnumerator GenerateMap(int seed, int difficulty)
        {
            loading.alpha = 1f;
            yield return null;
            
            Stopwatch stopwatch = Stopwatch.StartNew();
            mapGenerator.Generate(seed, difficulty);
            stopwatch.Stop();
            Debug.Log($"Generated map in {stopwatch.ElapsedMilliseconds}ms");
            
            loading.alpha = 0f;

            SceneManager.LoadScene(1);
        }
    }
}